package yanglib.session;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: user
 * Date: 9/12/14
 * Time: 5:09 PM
 * To change this template use File | Settings | File Templates.
 */
public class PendingRequest {
    private ClientSession session;
    private Request request;
    private Callback callback;
    private Set<Integer> targets;
    private long timeout;
    private HashMap<Integer, Reply> replies = new HashMap<Integer, Reply>();

    private long issueTime;

    private boolean completed = false;

    public PendingRequest(ClientSession session, Request request, Callback callback, Set<Integer> targets, long timeout){
        this.session = session;
        this.request = request;
        this.callback = callback;
        this.targets = targets;
        this.timeout = timeout;
        this.issueTime = System.currentTimeMillis();
    }

    public Request getRequest(){
        return this.request;
    }

    public Callback getCallback(){
        return this.callback;
    }



    public Set<Integer> getTargets(){
        return this.targets;
    }

    public Set<Integer> getUnRepliedTargets(){
        Set<Integer> ret = new HashSet<Integer>();
        for(Integer target : targets){
            if(!replies.containsKey(target))
                ret.add(target);
        }
        return ret;
    }

    public void addReply(Reply reply){
        replies.put(reply.getSender(), reply);
    }

    public Map<Integer, Reply> getReplies(){
        return replies;
    }

    protected boolean isCompleted(){
        return completed;
    }

    protected void setCompleted(){
        this.completed = true;
    }

    public void resend(Set<Integer> targets, long timeout){
        session.resend(this, targets, timeout);
    }

    protected void resetTimeout(long timeout){
        this.issueTime = System.currentTimeMillis();
        this.timeout = timeout;
    }

    public long getTimeOutTime(){
        return this.issueTime + timeout;
    }

}
